class GroupManager {
    constructor() {
        this.groupNameInput = document.getElementById('new-group-name-input');
        this.errorMessage = document.getElementById('group-name-error');
        this.confirmBtn = document.getElementById('new-group-conform-btn');
        this.userId = null;
        this.userName = null;

        this.initializeUser();
        this.bindEvents();
    }

    // 初始化用户数据
    async initializeUser() {
        try {
            const userData = await window.clickBtn.getUserDataObject();
            this.userId = userData.userId;
            this.userName = userData.userName;
        } catch (error) {
            console.error('获取用户信息失败:', error);
            this.errorMessage.textContent = '初始化失败，请刷新页面重试';
            this.errorMessage.classList.add('show');
        }
    }

    // 输入验证
    validateGroupName(name) {
        if (!name) {
            return '群组名称不能为空';
        }
        if (name.length < 2 || name.length > 20) {
            return '群组名称长度必须在2-20个字符之间';
        }
        return '';
    }

    // 绑定事件
    bindEvents() {
        // 输入框事件处理
        this.groupNameInput.addEventListener('input', () => {
            const error = this.validateGroupName(this.groupNameInput.value.trim());
            if (error) {
                this.groupNameInput.classList.add('input-invalid');
                this.errorMessage.textContent = error;
                this.errorMessage.classList.add('show');
            } else {
                this.groupNameInput.classList.remove('input-invalid');
                this.errorMessage.classList.remove('show');
            }
        });

        // 确认按钮点击事件
        this.confirmBtn.addEventListener('click', async () => {
            const groupName = this.groupNameInput.value.trim();
            const error = this.validateGroupName(groupName);
            
            if (error) {
                this.showErrorMessage(error);
                return;
            }

            try {
                this.confirmBtn.disabled = true;
                this.confirmBtn.textContent = '创建中...';
                
                const response = await fetch(`http://${_HOST_}:${_PORT_}/CreateGroup`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        userId: this.userId,
                        groupName: groupName
                    })
                });

                const result = await response.json();
                
                switch (result.code) {
                    case '0000':
                        this.showSuccessMessage(`群组"${groupName}"创建成功！`);
                        this.groupNameInput.value = '';
                        break;
                    case '1007':
                        this.showErrorMessage('群组名已存在');
                        break;
                    case '1002':
                        this.showErrorMessage('群组名称格式不正确');
                        break;
                    case '1003':
                        this.showErrorMessage('服务器错误，请稍后重试');
                        break;
                    default:
                        this.showErrorMessage('创建失败，请重试');
                }
            } catch (error) {
                console.error('创建群组失败:', error);
                this.showErrorMessage('网络错误，请检查网络连接');
            } finally {
                this.confirmBtn.disabled = false;
                this.confirmBtn.textContent = '创建群组';
            }
        });
    }

    // 新增显示错误消息的方法
    showErrorMessage(message) {
        this.groupNameInput.classList.add('input-invalid');
        this.errorMessage.style.color = '#dc3545';
        this.errorMessage.textContent = message;
        this.errorMessage.classList.add('show');
    }

    // 修改显示成功消息的方法
    showSuccessMessage(message) {
        this.groupNameInput.classList.remove('input-invalid');
        this.errorMessage.style.color = '#28a745';
        this.errorMessage.textContent = message;
        this.errorMessage.classList.add('show');
        
        setTimeout(() => {
            this.errorMessage.classList.remove('show');
            this.errorMessage.style.color = '#dc3545';
        }, 3000);
    }
}

// 初始化群组管理器
document.addEventListener('DOMContentLoaded', () => {
    const groupManager = new GroupManager();
});